package com.escom.info.scanner.jsf;

import com.escom.administracion.dao.UsuariosDAO;

import com.escom.administracionperfiles.hbm.dto.Usuarios;

import com.escom.cliente.exception.DAOException;

import com.escom.info.scanner.jsf.util.JsfUtil;
import com.escom.info.scanner.jsf.util.PaginationHelper;

import java.io.Serializable;
import java.util.List;

import java.util.ResourceBundle;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;

import javax.faces.model.SelectItem;


//@ManagedBean (name="usuariosController")
//@SessionScoped

public class UsuariosController implements Serializable{

    private Usuarios current;
    private DataModel items = null;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    private UsuariosDAO ejbFacade;

    public UsuariosDAO getEjbFacade() {
        return ejbFacade;
    }


    private UsuariosDAO getFacade() {

        return ejbFacade;
    }

    public void setEjbFacade(UsuariosDAO ejbFacade) {
        this.ejbFacade = ejbFacade;
    }

   





    
    public UsuariosController() {
    }

    public Usuarios getSelected() {
        if (current == null) {
            current = new Usuarios();
            selectedItemIndex = -1;
        }
        return current;
    }

    



    

    /*public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

              
                public int getItemsCount() {
                    return getFacade().count();
                }

              
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem()+getPageSize()}));
                }
            };
        }
        return pagination;
    }*/

    /*public String prepareList() {
        recreateModel();
        return "List";
    }*/

    /*public String prepareView() {
        current = (Usuarios)getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }*/

    public String prepareCreate() {
        current = new Usuarios();
        selectedItemIndex = -1;
        return "Create";
    }

  
    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage("Usuario fue capturado Satisfactoriamente");
            return prepareCreate();
        } catch (Exception e) {

            JsfUtil.addErrorMessage("Error el usuario no ha sido creado"); //AQUI ESTA
            return null;
        }
    }

    public String prepareEdit() {
        current = (Usuarios)getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

  
    public String update() {
        try {
            getFacade().editar(current);
            JsfUtil.addSuccessMessage("Usuario fue actualizado Satisfactoriamente");
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage("Error el usuario no ha sido actualizado"); //AQUI ESTA
            return null;
        }
    }

  
    public String destroy() {
        current = (Usuarios)getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remover(current);
            JsfUtil.addSuccessMessage("Usuario a sido eliminado Satisfactoriamente");
        } catch (Exception e) {
            JsfUtil.addErrorMessage("Error el usuario no ha sido eliminado"); //AQUI ESTA

        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count-1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
//            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex+1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
//            items = getPagination().createPageDataModel();
        }
        return items;
    }

  
    public List<Usuarios> getListaHistorialUsuarios()
    {
         List<Usuarios> usuarios=null;
        try{

           //if(usuarios)
           usuarios=getFacade().findAll();

        }catch(DAOException e){
            e.printStackTrace();
        }
          return usuarios;
    }
    private void recreateModel() {
        items = null;
    }

    public String next() {
//        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
  //      getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() throws DAOException {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() throws DAOException {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    



    @FacesConverter(forClass=Usuarios.class)
    public static class UsuariosControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
           try{
                if (value == null || value.length() == 0) {
                    return null;
                }
                UsuariosController controller = (UsuariosController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "usuariosController");
                return controller.ejbFacade.find(getKey(value));
           }catch(Exception e){
               e.printStackTrace();
           }
           return null;
           
        }

        java.lang.String getKey(String value) {
            java.lang.String key;
            key = value;
            return key;
        }

        String getStringKey(java.lang.String value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Usuarios) {
                Usuarios o = (Usuarios) object;
                return getStringKey(o.getDireccionIp());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: "+UsuariosController.class.getName());
            }
        }

    }

}
